﻿log("Running testGrab  ...")

//loadScriptAsync("./sizzle.min.js", main)
setTimeout(function ()
{
    loadScriptAsync("./jquery-2.1.4.min.js", function ()
    {
        setTimeout(function ()
        {
            main();
        }, 100);
    })
}, 1000)
//msg.send("itemFound",
//    {
//        "items":
//            {
//              "0":
//                  {
//                    "name": "腾讯QQ币100元qq币100Q币100qb币QB100个Q币直充★自动充值",
//                    "id": "5272733064",
//                    "shop": "福禄网游数卡专 营店",
//                    "imgsrc": "http://g-search1.alicdn.com/img/bao/uploaded/i4/i1/T1aiVpXoBHXXb1upjX.jpg_80x80.jpg",
//                    "link": "https://detail.tmall.com/item.htm?id=5272733064&ad_id=&am_id=&cm_id=140105335569ed55e27b&pm_id=&abbucket=0"
//                  },
//              "1":
//                  {
//                        "name": "腾讯1Q币/1q币1个1qb/1qq币QQ币1元Q币/1个Q币按元直充★自动充值",
//                        "id": "5450919622",
//                        "shop": "福禄网游数卡专营店",
//                        "imgsrc": "http://g-search1.alicdn.com/img/bao/uploaded/i4/i1/T1aiVpXoBHXXb1upjX.jpg_80x80.jpg",
//                        "link": "https://detail.tmall.com/item.htm?id=5450919622&ns=1&abbucket=0"
//                  },
//              "n": 1
//            }
//    }
//    )

const locations = {
    taobao: 1,
    searchingItem: 2,
    itemDetail: 3,
    unkonw : -1,
    current: function ()
    {
        var h = location.href;

        h = h.replace("https://", "");
        h = h.replace("http://", "");

        if (h.search("s.taobao.com/search?") === 0)
            return this.searchingItem;
        else if (h.search("www.taobao.com") === 0)
            return this.taobao;
        else if (h.search("detail.tmall.com/item.htm?") === 0)
            return this.itemDetail;
        return this.unkonw;
    }
}

// ----------------------
// DOM items
// ----------------------

function searchEdit()
{
    return $("input[name=q]")[0];
}

function searchButton()
{
    return $("[type=submit]", searchForm())[0];
}

function searchForm()
{
    return J_TSearchForm || J_SearchForm;
}

function nextPageButton()
{
    var j = $("a[title=下一页]");
    if(j.length === 0)
        j = $(":contains(下一页)").last();
    return j[0];
}

function toNextPage()
{
    var button = nextPageButton();
    if(button)
    {
        button.click();
    }
    else
    {
        location.href = location.href.replace(/&s=(\d+)/, function (a, b) { return "&s=" + (Number(d) + 10); })
    }
}

// ----
// node information
// ----

function getImageSrc(img)
{
    if(img.src)
        return https2http(img.src);
    var attr = img.getAttribute("data-ks-lazyload");
    if (!attr)
        return "http:" + attr;
    var attr = img.getAttribute("data-src");
    if (attr)
        return "http:" + attr;
    return "";
}

// ----------------------
// Helper functions
// ----------------------

var itemName = "足球";
var shopName = "老夏精品屋";

function reverseString(str)
{
    var s = "";
    for(var i = str.length - 1; i >= 0; i--)
    {
        s += str[i];
    }
    return s;
}

fixString = (function()
{
    var noWarp = /(\r|\n)/g;
    noWarp.compile(noWarp);
    var noFrontSpace = / */;
    noFrontSpace.compile(noFrontSpace);
    return function fixString(str)
    {
        str = str.replace(noWarp, "");
        return reverseString(reverseString(str.replace(noFrontSpace, "")).replace(noFrontSpace, ""));
    }
})();

function createKeywordSelector(searchStr, front, end)
{
    return createSelectorByKeyrowd(stringToKeywords(searchStr), front, end);
}

function createSelectorByKeyrowd(keys, front, end, sep)
{
    typeof front === "undefined" && (front = ":contains(");
    typeof end === "undefined" && (end = ")");
    typeof sep === "undefined" && (sep = ',');
    return front + keys.join(end + sep + front) + end;
}

function stringToKeywords(str)
{
    var keys = str.split(" ");
    var finalKeys = [];
    for (var i in keys)
    {
        finalKeys = finalKeys.concat(toggleString(keys[i]));
    }
    return finalKeys;
}

function toggleString(str)
{
    var strs = [str];
    for (var i in str)
    {
        i = Number(i);
        var c = str[i];
        if (c <= 'Z' && c >= 'A' || c <= 'z' && c >= 'a')
        {
            strs = extendOneBit(strs, i);
        }
    }
    return strs;
}

function extendOneBit(strs, bit)
{
    var add = [];
    for (var i in strs)
    {
        add[i] = toggleStrCase(strs[i], bit);
    }
    return add.concat(strs);
}

function toggleStrCase(str, bit)
{
    return str.substr(0, bit) + toggleCase(str[bit]) + str.substr(bit + 1);
}

function toggleCase(c)
{
    return c.charCodeAt(0) < 97 ? c.toLowerCase() : c.toUpperCase();
}

function https2http(url)
{
    return url.replace('https://', function ()
    {
        return "http://";
    })
}

// ----------------------
// Work flows
// ----------------------

function main()
{
    log("task start...");

    var data = msg.userdata('grabTest');
    var itemName = data.itemName;
    var shopName = data.shopName;
    log("itemName : " + itemName);
    log("shopName : " + shopName);

    switch (locations.current())
    {
        case locations.taobao:
            onTaobao();
            break;
        case locations.searchingItem:
            onSearchingItem();
            break;
        default:
            log("task : no task.")
            return;
    }

    function onTaobao()
    {
        log("task : onTaobao ...");

        msg.send("taobaoIndexOpened");

        tasks.search = function(arg)
        {
            searchEdit().value = arg.itemName;
            searchButton().click();
        }
    }
    function onSearchingItem()
    {
        log("task : onSearchingItem ...");
        search(0);
        function search(nth)
        {
            // find if shopname exist
            var jshops = $(createKeywordSelector(shopName, "span:contains(", ")"));
            var items = {};
            var itemNumber = 0;
            if (jshops.length)
            {

                var jimgs = {};
                var jtops = jshops;
                do
                {
                    jtops = jtops.parent()
                } while ((jimgs = jtops.find('img')).length == 0);
                var jlinks = jtops.find(createKeywordSelector(itemName, "span:contains(", ")")).parent();

                log("# of jshops : " + jshops.length);
                log("# of jtops : " + jtops.length);
                log("# of jimgs : " + jimgs.length);
                log("# of jlinks : " + jlinks.length);


                for (var i = 0; i < jshops.length; i++, itemNumber++)
                {
                    items[i] = {
                        index: i,
                        name: fixString(jlinks[i].textContent),
                        id: jlinks[i].getAttribute("data-nid"),
                        shop: fixString(jshops[i].textContent),
                        //imgsrc: https2http(jimgs[i].src),
                        imgsrc: getImageSrc(jimgs[i]),
                        //imgdata: getImageData(jimgs[i]),
                        link: jlinks[i].href,
                    };
                }

                log("task finished!");

            }
            tasks.acceptItem = function (arg)
            {
                if (arg.isFound === true)
                {
                    var acceptedItem = arg.item;
                    location.href = acceptedItem.link;
                }
            }
            tasks.searchNextPage = function (arg)
            {
                var currentLocation = location.href;
                toNextPage();
                function checkLoaded()
                {
                    if (location.href === currentLocation)
                        setTimeout(checkLoaded, 0);
                    else
                        search(nth + 1);
                };
                checkLoaded();
            }

            msg.send("itemFound",
                {
                    items: items,
                    n: itemNumber,
                    nth: nth
                });
            // waitting for server command.
        }


    }

}
/*
getImageData = (function (imgElement)
{
    var c = document.createElement("canvas");
    c.id = "mycanvas";
    document.body.appendChild(c);
    c = document.getElementById("mycanvas")
    return function (imgElement)
    {
        var ctx = c.getContext("2d");
        ctx.drawImage(imgElement, 0, 0);
        return ctx.getImageData(0, 0, imgElement.width, imgElement.height).toString();
    };
})()
*/